var tempI = 1;
var tempF = 1;
// 允许上传的图片类型
var allowTypes = ['image/jpg', 'image/jpeg', 'image/png', 'image/gif'];
// 1024KB，也就是 1MB
var maxSize = 1024 * 1024 * 2;
// 图片最大宽度
var maxWidth = 300;
// 最大上传图片数量
var maxCount = 4;
//上传文件
var $uploaderFiles = $('.weui_uploader_files');
// 删除文件按钮
var $delBtn = $('.weui-icon-delete');
// 上传的图片地址
var URL = '';
// 图片地址数组
var URLARR = [];
$(function () {


    $(".userid").val(sessionStorage.getItem("xt_userid"))
    $("#sendState-btn").click();
    $("#sendState-btn").change(function () {
        if ($(this).is(':checked')) {
            $(".if-can-postage").hide();
        } else {
            $(".if-can-postage").show();
        }
    });

    $("#if-proxy-btn").change(function () {
        if ($(this).is(':checked')) {
            $(".if-can-proxy").show();
            $("#proxy").val(1)

        } else {
            $(".if-can-proxy").hide();
            $("#proxy").val(0)
        }
    });
    $(".which-check").change(function () {
        if ($("#x11").is(':checked')) {
            location.href = 'release_product.html';

        } else {
            location.href = 'release_wannas.html';
        }
    });


    var tmpl = '<li class="weui-uploader__file" style="background-image:url(#url#)"></li>',
        $gallery = $("#gallery"), $galleryImg = $("#galleryImg"),
        $uploaderInput = $("#uploaderInput"),
        $uploaderFiles = $("#uploaderFiles")
    ;

    $uploaderInput.on("change", function (e) {
        var src, url = window.URL || window.webkitURL || window.mozURL, files = e.target.files;
        for (var i = 0, len = files.length; i < len; ++i) {
            var file = files[i];

            if (url) {
                src = url.createObjectURL(file);
            } else {
                src = e.target.result;
            }

            $uploaderFiles.append($(tmpl.replace('#url#', src)));
        }
    });


    $(".weui-uploader__file").on("click", "li", function () {
        $galleryImg.attr("style", this.getAttribute("style"));
        $gallery.fadeIn(100);
    });
    $gallery.on("click", function () {
        $gallery.fadeOut(100);
    });


    var auth = sessionStorage.getItem('hmdj_auth');
    // 设置初始是否包邮状态
    $('#sendState-btn').val('off');
    $('#sendState').val('false');
    // 将开关置为开启状态
    $('#sendState-btn').click();
    // 弹出提示
    // if (auth == 'true') {
    //     $('.is-auth').text('已认证');
    //     weui.alert('认证商家每天可以发布100单商品');
    //     $('.is-auth').on('click', function () {
    //         location.href = 'authentication2.html';
    //     });
    // } else {
    //     $('.is-auth').text('未认证');
    //     weui.alert('未认证商家每天仅可以发布10单商品，认证后将提高限额');
    //     $('.is-auth').on('click', function () {
    //         location.href = 'authentication.html';
    //     });
    // }
});


// 发布商品
$(document).on('click', '#showTooltips', function () {
    var params = {
        detail: $.trim($('.detail').val()),
        price: parseInt($.trim($('.price').val())),
    };
    for (var i in params) {
        if (params[i] == '') {
            weui.alert('请完善信息');
            return false;
        }
    }
    // 价格格式验证
    var d = params.price,
        regu = "^[0-9]{0,3}$",
        re = new RegExp(regu);
    if (!re.test(d)) {
        weui.alert('价格输入有误');
        return false;
    }
    // 图片验证
    // if (URLARR.length < 1) {
    //     weui.alert('请至少上传一张图片');
    //     return false;
    // }
    var loading = weui.loading('loading', {
        className: 'custom-classname'
    });


    var formData = new FormData($('#uploadform')[0]);
    var result = Model.wannas.uploadsWannas.do(formData);
    setTimeout(function () {
        if (result.code) {
            loading.hide();
            weui.toast('发布成功', {
                duration: 1500,
                className: 'custom-classname',
                callback: function () {
                    location.href = '../wannas.html';
                }
            });
        } else {
            loading.hide();
            weui.toast('发布失败', {
                duration: 1500,
                className: 'custom-classname',
                callback: function () {
                    location.href = 'release_product.html';
                }
            });
        }


    }, 1000);


// 删除图片按钮
    $(document).on('click', '.close-btn', function () {
        var id = $(this).attr('data-id');
        // 删除数组中该图片
        for (var i = 0; i < URLARR.length; i++) {
            if (URLARR[i].id == id) {
                URLARR.splice(i, 1);
            }
        }
        // 删除缩略图
        $(this).parent().remove();
    });

});


function fileChange(obj) {
    var files = obj[0].files;
    // 如果没有选中文件，直接返回
    if (files.length === 0) {
        return;
    }
    for (var i = 0, len = files.length; i < len; i++) {
        var file = files[i];
        var reader = new FileReader();
        // 如果类型不在允许的类型范围内
        if (allowTypes.indexOf(file.type) === -1) {
            weui.alert('该类型不允许上传');
            continue;
        }
        if (file.size > maxSize) {
            weui.alert('图片太大，不允许上传');
            continue;
        }
        reader.onload = function (e) {
            var img = new Image();
            var time = new Date().getTime();
            var fileid = "file" + time;
            img.onload = function () {
                // 不要超出最大宽度
                var w = Math.min(maxWidth, img.width);
                // 高度按比例计算
                var h = img.height * (w / img.width);
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext('2d');
                // 设置 canvas 的宽度和高度
                canvas.width = w;
                canvas.height = h;
                ctx.drawImage(img, 0, 0, w, h);
                var base64 = canvas.toDataURL('image/png');
                // 插入到预览区
                var $preview = $('<li class="weui_uploader_file weui_uploader_status" data-num="' + tempI + '" id="' + fileid + '" style="background-image:url(' + base64 + ');position: relative;"><a href="javascript:;" class="close-btn"><img src="../img/icon/close.png" class="upload-item-close"></a><div class="weui_uploader_status_content">0%</div></li>');
                $uploaderFiles.append($preview);
                var num = URLARR.length;
                // 删除图片按钮
                $('.close-btn').on('click', function () {
                    var that = $(this).parent();
                    delBtn(that);
                });

                //点击删除按钮，删除相应已上传图片
                function delBtn(that) {
                    // 删除对应的上传文件
                    var item = that.attr('data-num');
                    $('#file-' + item).remove();
                    //对应的图片删除
                    that.remove();
                    //删除后，重新计算当前剩余图片数量 end
                    // 删除数组中对应的图片信息
                    for (var i = 0; i < URLARR.length; i++) {
                        if (URLARR[i].id == item) {
                            URLARR.splice(i, 1);
                        }
                    }
                }

                var progress = 0;

                function uploading() {
                    $preview.find('.weui_uploader_status_content').text(progress++ + '%');
                    // 上传文件个数大于最大个数时，提示最多只能上传图片数量，清空图片和计数器
                    if (URLARR.length >= maxCount) {
                        weui.alert('最多只能上传' + maxCount + '张图片');
                        $('.weui_uploader_files li:last').remove();
                        return false;
                    } else {
                        // 进度小于100%时，上传继续
                        if (progress <= 100) {
                            // 禁用上传按钮
                            $('#file-' + tempI).attr('disabled', true);
                            $('#showTooltips').removeClass('submit-btn');
                            // $('#showTooltips').text('图片上传中...');
                            setTimeout(uploading, 20);
                        } else {
                            // 进度达到100%时，上传完毕，并当上传数量至少大于1时，提示文件上传成功
                            // 如果是失败，塞一个失败图标
                            $preview.removeClass('weui_uploader_status').find('.weui_uploader_status_content').remove();
                            $('.uploads-files').append(obj);
                            obj.css('display', 'none');
                            obj.attr('disabled', false);
                            // 进行图片上传

                            // 生成新的input
                            $('#uploader-wrapper').append('<input class="weui_uploader_input js_file" name="file" id="file-' + tempI + '" type="file" accept="image/jpg,image/jpeg,image/png,image/gif" multiple="multiple" onchange="fileChange($(this))" />');
                        }
                    }
                }

                setTimeout(uploading, 20);
            };
            img.src = e.target.result;
        };
        reader.readAsDataURL(file);
    }
}
